<?php
require_once("../../resources/commons.php");
require_once("dashboard_commons.php");
require_once("../../data/User.php");
require_once("../../data/Item.php");
require_once("../../data/Activity.php");
require_once("HTML/QuickForm/Controller.php");
require_once("HTML/QuickForm/Action/Display.php");
require_once("HTML/QuickForm/Action/Submit.php");
require_once("HTML/QuickForm/text.php");
require_once("HTML/QuickForm/textarea.php");
require_once("HTML/QuickForm/password.php");
require_once("HTML/QuickForm/submit.php");
require_once("HTML/QuickForm/select.php");
require_once("HTML/QuickForm/date.php");
require_once("HTML/QuickForm/static.php");

/**
 * Action creation form.<br/>
 * Form to be used by a user to create a new action.
 */
class AddActionPage extends HTML_QuickForm_Page{
    function buildForm(){
        $this->_formBuilt = true;
        
//JavaScript function which provides a filtering features for the select element
$l_filterScript=<<<EOT
<script type="text/javascript">
<!--
var fullOptionsArray;
/**
 * Filter the options according to the filter value.
 */
function filterOptions(myForm){
	if(fullOptionsArray==null){
		fullOptionsArray=new Array();
		for(i=0;i<myForm.activity.options.length;i++){
			fullOptionsArray[i]=new Option();
			fullOptionsArray[i].text=myForm.activity.options[i].text;
			fullOptionsArray[i].value=myForm.activity.options[i].value;
		}
	}
	var l_filterText=myForm.filter.value.replace(/^\s+|\s+$/g,"").toLowerCase();
	myForm.activity.options.length=0;
	var j=0;
	for(i=0;i<fullOptionsArray.length;i++){
		if(l_filterText=="" || fullOptionsArray[i].text.toLowerCase().indexOf(l_filterText)==0){
			var l_option=fullOptionsArray[i];
			myForm.activity.options[j++]=new Option(l_option.text, l_option.value, false);
		}
	}	
}
-->
</script>
<i>Filter the activity selecton:</i><br/>
<input type="text" name="filter" onKeyUp="filterOptions(this.form)" style="background-color: #CCCCCC;"/>
EOT;

        
        $l_filterInput=new HTML_Quickform_static("filter");
        $l_filterInput->setText($l_filterScript);
        $this->addElement($l_filterInput);
        
		$l_activitySelect=new HTML_QuickForm_select("activity");
		$l_activitySelect->setSize(5);
		$l_activitySelect->setLabel("Activity:");
		$l_records=Activity::getFromCustomCriteria(
			"WHERE isArchived=:isArchived",
			array("isArchived" => false));
		foreach($l_records as $l_activity){
			$l_activitySelect->addOption($l_activity->getTitle(),base64_encode($l_activity->getId()));
		}
		$this->addElement($l_activitySelect);

		$l_titleInput=new HTML_QuickForm_text("title");
		$l_titleInput->setLabel("Title:");
		$l_titleInput->setSize(60);
		$this->addElement($l_titleInput);
		
		$l_descriptionInput=new HTML_QuickForm_textarea("description");
		$l_descriptionInput->setLabel("Description:");
		$l_descriptionInput->setCols(60);
		$l_descriptionInput->setRows(5);
		$this->addElement($l_descriptionInput);
		
		$l_targetDateInput=new HTML_QuickForm_date("targetDate",null,
			array(
				"format" => "Y-m-d",
				"maxYear" =>date("Y", time())+2,
				"minYear" =>date("Y", time())));
		$l_targetDateInput->setLabel("Target date:");
		$this->addElement($l_targetDateInput);
		
		$l_allocatedUserSelect=new HTML_QuickForm_select("allocatedUser");
		$l_allocatedUserSelect->setLabel("Allocate to:");
		/*$l_records=User::getFromCustomCriteria(
			"WHERE isActive=:isActive and not id=:id",
			array("isActive" => true, "id" => SessionManager::getCurrentLoggedUserId()));*/
		$l_records=User::getFromCustomCriteria(
			"WHERE isActive=:isActive",
			array("isActive" => true));
		$l_allocatedUserSelect->addOption("No one","null");
		foreach($l_records as $l_user){
			$l_allocatedUserSelect->addOption($l_user->getFullName(),base64_encode($l_user->getId()));
		}
		$this->addElement($l_allocatedUserSelect);
		
		
		$l_submit=new HTML_QuickForm_submit("submit");
		$l_submit->setValue("OK");
		$this->addElement($l_submit);
		
		//The validation rules (either client and server)
		$this->registerRule("checkDate", "callback", "isDateValid");
		$this->addRule("targetDate", "The specified target date is not valid", "checkDate");
		$this->addRule("title","Title must not be empty","required",null,"client");
		$this->addRule("title","Title must not be empty","required",null,"server");
		$this->addRule("activity","Activity must not be empty","required",null,"client");
		$this->addRule("activity","Activity must not be empty","required",null,"server");
		
		$this->applyFilter("title","trim");
		$this->applyFilter("description","trim");
		
        $this->setDefaultAction("submit");
    }
}

/**
 * We subclass the default 'display' handler to customize the output
 */
class ActionDisplay extends HTML_QuickForm_Action_Display{
    function _renderForm($page){   	
    	SessionManager::getInstance()->checkSession();
    	displayTop("Create new action","../../resources/htmledit.php",null);
        $page->display();
        displayBottom();
    }
}

/**
 * Action to be called after a submit action.<br>
 * Send an invitation to the user with a link
 * to be used to access the registration screen.
 */
class ActionProcess extends HTML_QuickForm_Action{
    function perform($page){
    	SessionManager::getInstance()->checkSession();
    	
    	$l_action=new Item();
    	$l_action->setActivity_id(base64_decode($page->exportValue("activity")));
    	$l_action->setTitle($page->exportValue("title"));
    	$l_action->setDescription($page->exportValue("description"));
    	$l_action->setItemType_id(Item::ACTION_TYPE);
    	$l_action->setItemStatus_id(Item::ACTION_STATUS_OPENED);
    	$l_action->setCreatingUser_id(SessionManager::getCurrentLoggedUserId());
    	$l_action->setCreated(date("Y/m/d", time()));
    	$l_targetDate=$page->exportValue("targetDate");
    	$l_action->setTargetDate($l_targetDate["Y"]."/".$l_targetDate["m"]."/".$l_targetDate["d"]);
    	$l_allocatedUserId=$page->exportValue("allocatedUser");
    	if($l_allocatedUserId!="null"){
    		$l_action->setAllocatedUser_id(base64_decode($l_allocatedUserId));
    		$l_action->setAllocated(date("Y/m/d", time()));
    	}
    	$l_action->save();
    	
    	//Send notification
    	if($l_allocatedUserId!="null"){
	    	$l_allocatedUser=User::getFromPrimaryKey(base64_decode($l_allocatedUserId));
	    	notifyNewAction($l_allocatedUser->getEmail(),$l_action);
    	}
    	
    	HTTP::redirect("index.php");
    }
}

$controller =new HTML_QuickForm_Controller('ActionCreationProcess', false);
$controller->container(true);
$controller->setDefaults(
	array("targetDate" => date("Y-m-d", time()))
);
$controller->addPage(new AddActionPage('actionCreationPage'));
$controller->addAction('display', new ActionDisplay());
$controller->addAction('process', new ActionProcess());
$controller->addAction('submit', new HTML_QuickForm_Action_Submit());
$controller->run();

?>